using System.Text;
using System.Text.Json;
using HtmlAgilityPack;
using DaoHang.Models;

namespace DaoHang.Services
{
    /// <summary>
    /// 阿里云百炼AI服务实现类
    /// </summary>
    public class AliCloudAIService : IAliCloudAIService
    {
        private readonly HttpClient httpClient;
        private readonly ILogger<AliCloudAIService> logger;
        private readonly ISiteSettingsService siteSettingsService;

        // 固定的AI配置
        private const string API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        private const string MODEL_NAME = "qwen3-235b-a22b";
        private const int TIMEOUT_SECONDS = 120; // 调整超时时间到2分钟
        private const double TEMPERATURE = 0.7;
        private const int MAX_TOKENS = 3000; // 增加最大token数以支持更多推荐内容

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpClient">HTTP客户端</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="siteSettingsService">网站设置服务</param>
        public AliCloudAIService(HttpClient httpClient, ILogger<AliCloudAIService> logger, ISiteSettingsService siteSettingsService)
        {
            this.httpClient = httpClient;
            this.logger = logger;
            this.siteSettingsService = siteSettingsService;
            
            // 配置HTTP客户端
            this.httpClient.Timeout = TimeSpan.FromSeconds(TIMEOUT_SECONDS);
        }

        /// <summary>
        /// 获取当前有效的AI配置
        /// </summary>
        /// <returns>AI配置</returns>
        private async Task<AIConfig?> GetCurrentConfigAsync()
        {
            try
            {
                var siteSettings = await siteSettingsService.GetSiteSettingsAsync();
                if (siteSettings == null || string.IsNullOrEmpty(siteSettings.AliCloudApiKey))
                {
                    logger.LogWarning("未配置API密钥，请在网站设置中配置阿里云API密钥");
                    return null;
                }

                return new AIConfig
                {
                    ApiKey = siteSettings.AliCloudApiKey,
                    ApiUrl = API_URL,
                    ModelName = MODEL_NAME,
                    Provider = "阿里云",
                    IsEnabled = true,
                    TimeoutSeconds = TIMEOUT_SECONDS,
                    Temperature = TEMPERATURE,
                    MaxTokens = MAX_TOKENS
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取AI配置失败");
                return null;
            }
        }

        /// <summary>
        /// 总结网页内容
        /// </summary>
        /// <param name="url">网页URL</param>
        /// <param name="content">网页内容（可选）</param>
        /// <returns>总结结果</returns>
        public async Task<AISummaryResult> SummarizeWebContentAsync(string url, string? content = null)
        {
            var result = new AISummaryResult();

            try
            {
                var config = await GetCurrentConfigAsync();
                if (config == null || string.IsNullOrEmpty(config.ApiKey))
                {
                    result.ErrorMessage = "未配置阿里云API密钥";
                    return result;
                }

                // 如果没有提供内容，尝试获取网页内容
                if (string.IsNullOrEmpty(content))
                {
                    content = await GetWebPageContentAsync(url);
                }

                if (string.IsNullOrEmpty(content))
                {
                    result.ErrorMessage = "无法获取网页内容";
                    return result;
                }

                // 构建提示词
                var prompt = $@"请分析以下网站内容，并提供：
1. 网站的简要总结（50-100字）
2. 3-5个关键词
3. 建议的分类（从以下选择：搜索引擎、社交媒体、开发工具、新闻资讯、电商购物、教育学习、娱乐游戏、金融理财、生活服务、其他）

网站URL: {url}
网站内容: {content.Substring(0, Math.Min(content.Length, 2000))}

请以JSON格式返回结果：
{{
  ""summary"": ""网站总结"",
  ""keywords"": [""关键词1"", ""关键词2"", ""关键词3""],
  ""categories"": [""分类1"", ""分类2""]
}}";

                var response = await CallAliCloudAPIAsync(prompt, config.ApiKey, false);
                if (response.Success)
                {
                    result = ParseSummaryResponse(response.Content);
                    result.Success = true;
                }
                else
                {
                    result.ErrorMessage = response.ErrorMessage;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "总结网页内容时发生错误: {Url}", url);
                result.ErrorMessage = $"总结失败: {ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 生成网站描述
        /// </summary>
        /// <param name="title">网站标题</param>
        /// <param name="url">网站URL</param>
        /// <param name="content">网站内容</param>
        /// <returns>生成的描述</returns>
        public async Task<string> GenerateWebsiteDescriptionAsync(string title, string url, string? content = null)
        {
            try
            {
                var config = await GetCurrentConfigAsync();
                if (config == null || string.IsNullOrEmpty(config.ApiKey))
                {
                    return "未配置阿里云API密钥";
                }

                var prompt = $@"请为以下网站生成一个简洁、准确的描述（30-80字）：

网站标题: {title}
网站URL: {url}";

                if (!string.IsNullOrEmpty(content))
                {
                    prompt += $"\n网站内容: {content.Substring(0, Math.Min(content.Length, 1000))}";
                }

                prompt += "\n\n请直接返回描述文本，不需要其他格式。";

                var response = await CallAliCloudAPIAsync(prompt, config.ApiKey, false);
                if (response.Success)
                {
                    return response.Content.Trim().Trim('"');
                }
                else
                {
                    logger.LogWarning("生成网站描述失败: {Error}", response.ErrorMessage);
                    return $"基于{title}的网站服务";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "生成网站描述时发生错误: {Title}", title);
                return $"基于{title}的网站服务";
            }
        }

        /// <summary>
        /// 智能分类建议
        /// </summary>
        /// <param name="websiteTitle">网站标题</param>
        /// <param name="websiteDescription">网站描述</param>
        /// <param name="websiteUrl">网站URL</param>
        /// <returns>分类建议</returns>
        public async Task<List<string>> SuggestCategoriesAsync(string websiteTitle, string websiteDescription, string websiteUrl)
        {
            try
            {
                var config = await GetCurrentConfigAsync();
                if (config == null || string.IsNullOrEmpty(config.ApiKey))
                {
                    return new List<string> { "其他" };
                }

                var prompt = $@"根据以下网站信息，从这些分类中选择最合适的1-2个：
搜索引擎、社交媒体、开发工具、新闻资讯、电商购物、教育学习、娱乐游戏、金融理财、生活服务、其他

网站标题: {websiteTitle}
网站描述: {websiteDescription}
网站URL: {websiteUrl}

请只返回分类名称，用逗号分隔。";

                var response = await CallAliCloudAPIAsync(prompt, config.ApiKey, false);
                if (response.Success)
                {
                    var categories = response.Content
                        .Split(',', '，')
                        .Select(c => c.Trim())
                        .Where(c => !string.IsNullOrEmpty(c))
                        .ToList();
                    
                    return categories.Any() ? categories : new List<string> { "其他" };
                }
                else
                {
                    logger.LogWarning("智能分类建议失败: {Error}", response.ErrorMessage);
                    return new List<string> { "其他" };
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "智能分类建议时发生错误: {Title}", websiteTitle);
                return new List<string> { "其他" };
            }
        }

        /// <summary>
        /// 调用阿里云API（兼容OpenAI格式，支持结构化输出）
        /// </summary>
        /// <param name="prompt">提示词</param>
        /// <param name="apiKey">API密钥</param>
        /// <param name="useStructuredOutput">是否使用结构化输出</param>
        /// <returns>API响应</returns>
        private async Task<(bool Success, string Content, string ErrorMessage)> CallAliCloudAPIAsync(string prompt, string apiKey, bool useStructuredOutput = false)
        {
            try
            {
                // 使用兼容OpenAI的API格式
                var requestBody = new
                {
                    model = MODEL_NAME,
                    messages = new[]
                    {
                        new
                        {
                            role = "system",
                            content = "你是一个专业的网站推荐助手，能够根据分类推荐高质量的网站。请严格按照要求的JSON格式返回结果。"
                        },
                        new
                        {
                            role = "user",
                            content = prompt
                        }
                    },
                    max_tokens = MAX_TOKENS,
                    temperature = TEMPERATURE,
                    stream = false,
                    // 使用结构化输出确保返回标准JSON格式
                    response_format = useStructuredOutput ? new { type = "json_object" } : null
                };

                var json = JsonSerializer.Serialize(requestBody, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
                });
                
                logger.LogDebug("发送API请求: {Request}", json);
                
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                // 设置请求头
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

                // 使用固定的API端点
                var response = await httpClient.PostAsync(API_URL, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                logger.LogDebug("API响应状态: {StatusCode}, 内容长度: {Length}", response.StatusCode, responseContent.Length);

                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = JsonDocument.Parse(responseContent);
                    var root = jsonResponse.RootElement;
                    
                    // 解析兼容OpenAI格式的响应
                    if (root.TryGetProperty("choices", out var choices) && choices.ValueKind == JsonValueKind.Array)
                    {
                        var firstChoice = choices.EnumerateArray().FirstOrDefault();
                        if (firstChoice.ValueKind != JsonValueKind.Undefined &&
                            firstChoice.TryGetProperty("message", out var message) &&
                            message.TryGetProperty("content", out var messageContent))
                        {
                            var text = messageContent.GetString() ?? "";
                            logger.LogDebug("API返回内容: {Content}", text.Substring(0, Math.Min(text.Length, 200)));
                            return (true, text, "");
                        }
                    }
                    
                    logger.LogWarning("API响应格式不符合预期: {Content}", responseContent);
                    return (false, "", "API响应格式错误");
                }
                else
                {
                    logger.LogError("阿里云API调用失败: {StatusCode} - {Content}", response.StatusCode, responseContent);
                    return (false, "", $"API调用失败: {response.StatusCode} - {responseContent}");
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "调用阿里云API时发生错误");
                return (false, "", $"API调用异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取网页内容
        /// </summary>
        /// <param name="url">网页URL</param>
        /// <returns>网页文本内容</returns>
        private async Task<string> GetWebPageContentAsync(string url)
        {
            try
            {
                var response = await httpClient.GetAsync(url);
                if (!response.IsSuccessStatusCode)
                {
                    return "";
                }

                var html = await response.Content.ReadAsStringAsync();
                var doc = new HtmlDocument();
                doc.LoadHtml(html);

                // 移除脚本和样式标签
                var scriptsAndStyles = doc.DocumentNode.SelectNodes("//script | //style");
                if (scriptsAndStyles != null)
                {
                    foreach (var node in scriptsAndStyles)
                    {
                        node.Remove();
                    }
                }

                // 获取主要内容
                var bodyText = doc.DocumentNode.SelectSingleNode("//body")?.InnerText ?? "";
                
                // 清理文本
                bodyText = System.Text.RegularExpressions.Regex.Replace(bodyText, @"\s+", " ");
                bodyText = bodyText.Trim();

                // 限制长度
                return bodyText.Length > 3000 ? bodyText.Substring(0, 3000) : bodyText;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取网页内容失败: {Url}", url);
                return "";
            }
        }

        /// <summary>
        /// 解析总结响应
        /// </summary>
        /// <param name="responseContent">响应内容</param>
        /// <returns>解析结果</returns>
        private AISummaryResult ParseSummaryResponse(string responseContent)
        {
            var result = new AISummaryResult();

            try
            {
                // 尝试解析JSON响应
                var jsonDoc = JsonDocument.Parse(responseContent);
                var root = jsonDoc.RootElement;

                if (root.TryGetProperty("summary", out var summaryElement))
                {
                    result.Summary = summaryElement.GetString() ?? "";
                }

                if (root.TryGetProperty("keywords", out var keywordsElement) && keywordsElement.ValueKind == JsonValueKind.Array)
                {
                    result.Keywords = keywordsElement.EnumerateArray()
                        .Select(e => e.GetString() ?? "")
                        .Where(s => !string.IsNullOrEmpty(s))
                        .ToList();
                }

                if (root.TryGetProperty("categories", out var categoriesElement) && categoriesElement.ValueKind == JsonValueKind.Array)
                {
                    result.SuggestedCategories = categoriesElement.EnumerateArray()
                        .Select(e => e.GetString() ?? "")
                        .Where(s => !string.IsNullOrEmpty(s))
                        .ToList();
                }
            }
            catch (JsonException)
            {
                // 如果不是JSON格式，直接作为总结内容
                result.Summary = responseContent.Trim();
            }

            return result;
        }

        /// <summary>
        /// 生成网站内容摘要
        /// </summary>
        /// <param name="content">网站内容</param>
        /// <param name="url">网站URL</param>
        /// <returns>生成的摘要</returns>
        public async Task<string> GenerateSummaryAsync(string content, string url)
        {
            try
            {
                var config = await GetCurrentConfigAsync();
                if (config == null || string.IsNullOrEmpty(config.ApiKey))
                {
                    return "未配置阿里云API密钥";
                }

                if (string.IsNullOrEmpty(content))
                {
                    return "无法获取网站内容";
                }

                var prompt = $@"请为以下网站内容生成一个简洁、准确的描述（50-100字）：

网站URL: {url}
网站内容: {content.Substring(0, Math.Min(content.Length, 2000))}

要求：
1. 描述要准确反映网站的主要功能和特色
2. 语言简洁明了，避免冗余
3. 突出网站的核心价值
4. 直接返回描述文本，不需要其他格式

请生成描述：";

                var response = await CallAliCloudAPIAsync(prompt, config.ApiKey, false);
                if (response.Success)
                {
                    return response.Content.Trim().Trim('"');
                }
                else
                {
                    logger.LogWarning("生成网站摘要失败: {Error}", response.ErrorMessage);
                    return "智能网站服务平台";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "生成网站摘要时发生错误: {Url}", url);
                return "智能网站服务平台";
            }
        }

        /// <summary>
        /// 根据分类推荐网站
        /// </summary>
        /// <param name="categoryName">分类名称</param>
        /// <param name="categoryDescription">分类描述</param>
        /// <param name="existingWebsites">已有网站列表（用于避免重复推荐）</param>
        /// <param name="count">推荐数量</param>
        /// <param name="preferChineseWebsites">是否优先推荐中国网站</param>
        /// <returns>推荐的网站列表</returns>
        public async Task<List<RecommendedWebsite>> RecommendWebsitesByCategoryAsync(string categoryName, string? categoryDescription = null, List<string>? existingWebsites = null, int count = 20, bool preferChineseWebsites = true)
        {
            try
            {
                var config = await GetCurrentConfigAsync();
                if (config == null || string.IsNullOrEmpty(config.ApiKey))
                {
                    logger.LogWarning("未配置阿里云API密钥，无法进行网站推荐");
                    return new List<RecommendedWebsite>();
                }

                var existingList = existingWebsites ?? new List<string>();
                var existingWebsitesText = existingList.Any() 
                    ? $"\n\n已有网站（请避免推荐重复的）：\n{string.Join("\n", existingList)}" 
                    : "";

                // 根据用户偏好和分类特性确定地域偏好
                var isSpecialCategory = IsSpecialCategory(categoryName);
                string regionPreference;
                
                if (preferChineseWebsites && !isSpecialCategory)
                {
                    regionPreference = "优先推荐中国的网站，如果中国网站不足，再补充国外知名网站";
                }
                else if (preferChineseWebsites && isSpecialCategory)
                {
                    regionPreference = "推荐国际知名网站，但在同等质量下优先选择中国网站";
                }
                else
                {
                    regionPreference = "推荐国际知名网站，包括中国和国外的优质网站，不区分地域";
                }

                var prompt = $@"你需要为""{categoryName}""分类推荐{count}个优质网站，提取出name（网站名称，为string类型）、url（网站地址，为string类型）、description（网站描述，为string类型）、reason（推荐理由，为string类型）、score（评分，为number类型），请输出JSON字符串，不要输出其它无关内容。

分类信息：
- 分类名称：{categoryName}
- 分类描述：{categoryDescription ?? "无特定描述"}
{existingWebsitesText}

地域偏好：{regionPreference}

推荐要求：
1. 推荐知名度高、用户活跃度高的优质网站
2. 网站必须与""{categoryName}""分类高度相关
3. 提供真实可访问的网站URL（必须包含完整的https://协议）
4. 网站名称使用官方准确名称
5. 网站描述详细准确（50-100字），突出核心功能和特色
6. 推荐理由具体明确（30-60字），说明适合此分类的原因
7. 评分合理（1-10分），基于知名度、用户体验、内容质量
8. 严格推荐{count}个网站，不多不少
9. 避免已关闭、无法访问或质量低下的网站
10. 确保URL格式正确，可以直接访问

示例：
Q：为""搜索引擎""分类推荐2个网站
A：{{""websites"":[{{""name"":""Google"",""url"":""https://www.google.com"",""description"":""全球最大的搜索引擎，提供网页、图片、视频等全方位搜索服务，搜索结果准确快速，是互联网用户的首选搜索工具"",""reason"":""搜索引擎领域的绝对领导者，技术先进，用户体验优秀"",""score"":10}},{{""name"":""百度"",""url"":""https://www.baidu.com"",""description"":""中国最大的搜索引擎，专注中文搜索，提供网页、新闻、图片、视频等搜索服务，深度理解中文语义"",""reason"":""中文搜索领域的领导者，更适合中国用户使用习惯"",""score"":9}}]}}

Q：为""{categoryName}""分类推荐{count}个网站
A：";

                var response = await CallAliCloudAPIAsync(prompt, config.ApiKey, true);
                if (response.Success)
                {
                    return ParseRecommendationResponse(response.Content);
                }
                else
                {
                    logger.LogWarning("AI网站推荐失败: {Error}", response.ErrorMessage);
                    return new List<RecommendedWebsite>();
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "AI网站推荐时发生错误: {Category}", categoryName);
                return new List<RecommendedWebsite>();
            }
        }

        /// <summary>
        /// 解析推荐响应（结构化输出版本）
        /// </summary>
        /// <param name="responseContent">响应内容</param>
        /// <returns>推荐网站列表</returns>
        private List<RecommendedWebsite> ParseRecommendationResponse(string responseContent)
        {
            var recommendations = new List<RecommendedWebsite>();

            try
            {
                logger.LogInformation("开始解析AI推荐响应，内容长度: {Length}", responseContent.Length);
                logger.LogDebug("AI返回的JSON内容: {Content}", responseContent);

                // 使用结构化输出后，响应应该是标准JSON格式，直接解析
                var jsonDoc = JsonDocument.Parse(responseContent);
                var root = jsonDoc.RootElement;

                if (root.TryGetProperty("websites", out var websitesElement) && websitesElement.ValueKind == JsonValueKind.Array)
                {
                    foreach (var websiteElement in websitesElement.EnumerateArray())
                    {
                        var website = new RecommendedWebsite();

                        if (websiteElement.TryGetProperty("name", out var nameElement))
                        {
                            website.Name = nameElement.GetString() ?? "";
                        }

                        if (websiteElement.TryGetProperty("url", out var urlElement))
                        {
                            website.Url = urlElement.GetString() ?? "";
                        }

                        if (websiteElement.TryGetProperty("description", out var descElement))
                        {
                            website.Description = descElement.GetString() ?? "";
                        }

                        if (websiteElement.TryGetProperty("reason", out var reasonElement))
                        {
                            website.Reason = reasonElement.GetString() ?? "";
                        }

                        if (websiteElement.TryGetProperty("score", out var scoreElement))
                        {
                            // 支持数字和字符串格式的评分
                            if (scoreElement.ValueKind == JsonValueKind.Number)
                            {
                                website.Score = scoreElement.GetInt32();
                            }
                            else if (scoreElement.ValueKind == JsonValueKind.String)
                            {
                                if (int.TryParse(scoreElement.GetString(), out var score))
                                {
                                    website.Score = score;
                                }
                                else
                                {
                                    website.Score = 7; // 默认评分
                                }
                            }
                        }

                        // 验证必要字段和数据质量
                        if (!string.IsNullOrEmpty(website.Name) && 
                            !string.IsNullOrEmpty(website.Url) && 
                            IsValidWebsiteUrl(website.Url))
                        {
                            // 确保评分在合理范围内
                            if (website.Score < 1) website.Score = 1;
                            if (website.Score > 10) website.Score = 10;
                            
                            // 确保描述和理由不为空
                            if (string.IsNullOrEmpty(website.Description))
                                website.Description = "优质网站，值得推荐";
                            if (string.IsNullOrEmpty(website.Reason))
                                website.Reason = "符合分类要求的优质网站";
                            
                            recommendations.Add(website);
                            logger.LogDebug("成功解析网站: {Name} - {Url}", website.Name, website.Url);
                        }
                        else
                        {
                            logger.LogWarning("跳过无效的推荐网站: Name={Name}, Url={Url}", website.Name, website.Url);
                        }
                    }
                }
                else
                {
                    logger.LogWarning("响应中未找到websites数组，尝试备用解析");
                    recommendations = ParseRecommendationFromText(responseContent);
                }

                logger.LogInformation("成功解析{Count}个推荐网站", recommendations.Count);
            }
            catch (JsonException ex)
            {
                logger.LogError(ex, "JSON解析失败，错误位置: 行{Line}, 字节位置{Position}", 
                    ex.LineNumber, ex.BytePositionInLine);
                logger.LogError("JSON解析失败的内容: {Content}", responseContent);
                
                // 如果结构化输出失败，尝试备用解析
                recommendations = ParseRecommendationFromText(responseContent);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "解析AI推荐响应时发生未知错误");
                recommendations = ParseRecommendationFromText(responseContent);
            }

            return recommendations;
        }

        /// <summary>
        /// 清理JSON内容，移除干扰字符和格式
        /// </summary>
        /// <param name="content">原始内容</param>
        /// <returns>清理后的JSON内容</returns>
        private string CleanJsonContent(string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;

            try
            {
                var cleanContent = content.Trim();
                
                // 移除markdown代码块标记
                if (cleanContent.StartsWith("```json"))
                {
                    cleanContent = cleanContent.Substring(7);
                }
                else if (cleanContent.StartsWith("```"))
                {
                    cleanContent = cleanContent.Substring(3);
                }
                
                if (cleanContent.EndsWith("```"))
                {
                    cleanContent = cleanContent.Substring(0, cleanContent.Length - 3);
                }
                
                cleanContent = cleanContent.Trim();
                
                // 查找JSON开始和结束位置
                var jsonStart = cleanContent.IndexOf('{');
                var jsonEnd = cleanContent.LastIndexOf('}');
                
                if (jsonStart >= 0 && jsonEnd > jsonStart)
                {
                    cleanContent = cleanContent.Substring(jsonStart, jsonEnd - jsonStart + 1);
                }
                
                // 移除可能的BOM和其他不可见字符
                cleanContent = cleanContent.Replace("\uFEFF", ""); // BOM
                cleanContent = cleanContent.Replace("\0", ""); // NULL字符
                
                // 确保JSON完整性 - 检查括号匹配
                var openBraces = cleanContent.Count(c => c == '{');
                var closeBraces = cleanContent.Count(c => c == '}');
                
                if (openBraces > closeBraces)
                {
                    // 添加缺失的右括号
                    cleanContent += new string('}', openBraces - closeBraces);
                }
                
                // 检查数组括号
                var openBrackets = cleanContent.Count(c => c == '[');
                var closeBrackets = cleanContent.Count(c => c == ']');
                
                if (openBrackets > closeBrackets)
                {
                    // 添加缺失的右方括号
                    cleanContent += new string(']', openBrackets - closeBrackets);
                }
                
                return cleanContent.Trim();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "清理JSON内容时发生错误");
                return content;
            }
        }

        /// <summary>
        /// 从文本中解析推荐（备用方案）
        /// </summary>
        /// <param name="text">文本内容</param>
        /// <returns>推荐网站列表</returns>
        private List<RecommendedWebsite> ParseRecommendationFromText(string text)
        {
            var recommendations = new List<RecommendedWebsite>();

            try
            {
                logger.LogWarning("JSON解析失败，尝试文本解析: {Text}", text.Substring(0, Math.Min(text.Length, 200)));
                
                // 简单的文本解析逻辑
                var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                
                foreach (var line in lines)
                {
                    // 查找包含URL的行
                    if (line.Contains("http") && (line.Contains(".com") || line.Contains(".org") || line.Contains(".net") || line.Contains(".cn")))
                    {
                        var website = new RecommendedWebsite();
                        
                        // 提取URL
                        var urlMatch = System.Text.RegularExpressions.Regex.Match(line, @"https?://[^\s\]]+");
                        if (urlMatch.Success)
                        {
                            website.Url = urlMatch.Value.TrimEnd(',', '.', ')', ']', '}');
                            
                            // 验证URL有效性
                            if (!IsValidWebsiteUrl(website.Url))
                                continue;
                            
                            // 尝试提取网站名称（URL前的文本）
                            var nameText = line.Substring(0, urlMatch.Index).Trim();
                            nameText = nameText.Replace("-", "").Replace("*", "").Replace("•", "").Trim();
                            
                            if (!string.IsNullOrEmpty(nameText) && nameText.Length > 2)
                            {
                                website.Name = nameText;
                            }
                            else
                            {
                                // 从URL提取域名作为名称
                                try
                                {
                                    var uri = new Uri(website.Url);
                                    website.Name = uri.Host.Replace("www.", "");
                                }
                                catch
                                {
                                    website.Name = "未知网站";
                                }
                            }
                            
                            // 尝试提取描述（URL后的文本）
                            var descText = line.Substring(urlMatch.Index + urlMatch.Length).Trim();
                            if (!string.IsNullOrEmpty(descText) && descText.Length > 10)
                            {
                                website.Description = descText.Length > 100 ? descText.Substring(0, 100) + "..." : descText;
                            }
                            else
                            {
                                website.Description = $"优质的{website.Name}网站，值得推荐";
                            }
                            
                            website.Reason = "AI推荐的优质网站";
                            website.Score = 7;
                            
                            recommendations.Add(website);
                        }
                    }
                }
                
                logger.LogInformation("文本解析完成，解析出{Count}个网站", recommendations.Count);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "从文本解析推荐失败");
            }

            return recommendations;
        }

        /// <summary>
        /// 验证网站URL是否有效
        /// </summary>
        /// <param name="url">要验证的URL</param>
        /// <returns>是否有效</returns>
        private bool IsValidWebsiteUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;

            try
            {
                var uri = new Uri(url);
                return (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) &&
                       !string.IsNullOrEmpty(uri.Host) &&
                       uri.Host.Contains('.'); // 确保有域名
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 判断是否为特殊分类（开发工具、技术相关等）
        /// </summary>
        /// <param name="categoryName">分类名称</param>
        /// <returns>是否为特殊分类</returns>
        private bool IsSpecialCategory(string categoryName)
        {
            var specialCategories = new[]
            {
                "开发工具", "编程", "技术", "代码", "GitHub", "开源",
                "API", "云服务", "服务器", "数据库", "框架", "库",
                "IDE", "编辑器", "版本控制", "DevOps", "运维",
                "人工智能", "机器学习", "深度学习", "算法",
                "区块链", "加密货币", "比特币"
            };

            return specialCategories.Any(special => 
                categoryName.Contains(special, StringComparison.OrdinalIgnoreCase));
        }
    }
} 